import { localSecretStorage, sessionSecretStorage } from "@/utils/ls.js";
import { defineStore } from "pinia";
import { authLogin, authLogout } from "@/api/account/index.js";
import { ElMessage } from "element-plus";

export const useAccountStore = defineStore("account", {
  state: () => ({
    token:
      localSecretStorage.get("token") ||
      sessionSecretStorage.get("token") ||
      "", // 认证令牌
    user:
      localSecretStorage.get("user") ||
      sessionSecretStorage.get("user") ||
      null, // 用户信息
  }),
  getters: {
    isAuthenticated: () => !!this.token, // 检查是否已认证
  },
  persist: {
    storage: sessionSecretStorage,
  },
  actions: {
    async login(credentials) {
      return await authLogin(credentials)
        .then((data) => {
          if (data) {
            // 登录成功，保存用户信息和令牌
            if (credentials.rememberMe) {
              localSecretStorage.set("token", data.token);
              localSecretStorage.set("user", data.username);
            } else {
              sessionSecretStorage.set("token", data.token);
              sessionSecretStorage.set("user", data.username);
            }
            this.token = data.token;
            this.user = data.username;
            return true;
          } else {
            return false;
          }
        })
        .catch((error) => {
          console.error("Login Error:", error);
          ElMessage.error("登录失败，请稍后重试！");
          return false;
        });
    },
    // 操作认证
    async authenticated() {
      // 检查是否已认证
      return Promise.resolve(
        !!localSecretStorage.get("token") || !!sessionStorage.getItem("token")
      );
    },
    async logout() {
      return await authLogout().then((data) => {
        if (data) {
          // 登出成功，清除用户信息和令牌
          this.token = null;
          this.user = null;
          localSecretStorage.clear();
          localSecretStorage.rem("token");
          sessionStorage.removeItem("token");
          sessionSecretStorage.clear();
          return true;
        } else {
          ElMessage.error("登出失败，请稍后重试！");
          return false;
        }
      });
    },
  },
});
